package utils;

import org.apache.commons.lang.StringUtils;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 视频流工具类
 *
 * @author zjh
 */
public class GrabberUtil {
    public static FFmpegFrameGrabber getGrabber(String url) {
        if (StringUtils.isEmpty(url)) {
            throw new RuntimeException("url不能为空");
        }
        try {
            FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(url);
            //设置tcp，要不然掉包严重
//            grabber.setOption("rtsp_transport", "tcp");
            return grabber;
        } catch (FrameGrabber.Exception e) {
            throw new RuntimeException("获取grabber失败",e);
        }
    }

    /**
     * 截取图片并缓存本地
     *
     * @param grabber 视频流
     * @param imageOutput 图片缓存地址
     * @param imageFormat 图片格式
     * @return 图片文件
     */
    public static File getIma(FFmpegFrameGrabber grabber, String imageOutput, String imageFormat) {
        File outPut = new File(imageOutput);
        while (true) {
            try {
                Frame frame = grabber.grabImage();
                if (frame != null) {
                    ImageIO.write(frameToBufferedImage(frame), imageFormat, outPut);
                    break;
                }
            } catch (IOException e) {
                outPut.delete();
                throw new RuntimeException("缓存图片出错", e);
            }
        }
        return outPut;
    }

    /**
     * 创建BufferedImage对象
     */
    public static BufferedImage frameToBufferedImage(Frame frame) {
        Java2DFrameConverter converter = new Java2DFrameConverter();
        //		bufferedImage=rotateClockwise90(bufferedImage);
        return converter.getBufferedImage(frame);
    }
}
